import { programData } from '@/store/modules/program/utils';
import { nanoid } from 'nanoid';
import { ref } from 'vue';

export const selectKeys = ref<Set<string>>(new Set());

function getPassword(length: number, includeSpecialCharacters: boolean) {
  let characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  if (includeSpecialCharacters) {
    characters += '!@#$%^&*()_+={}[]|<>';
  }

  let password = '';
  for (let i = 0; i < length; i += 1) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    password += characters.charAt(randomIndex);
  }

  return password;
}

export const generatePassword = (): string => {
  const data = programData();
  let password = '';

  const { passwordLength } = data.config;
  switch (data.config.passwordType) {
    case 'normal':
      password = getPassword(passwordLength, false);
      break;
    case 'special':
      password = getPassword(passwordLength, true);
      break;

    default:
      break;
  }
  return password;
};
/* 创建一个新的记录，清空已选择，将新的记录添加进去 */
export const create = () => {
  selectKeys.value.clear();
  const data = programData();

  const id = nanoid();
  data.list.unshift({
    title: '无标题',
    account: '',
    password: generatePassword(),
    id,
    date: new Date().toDateString(),
    desc: '',
  });
  selectKeys.value.add(id);
};
